<?php
namespace Admin\Controller;
class GoodsController extends BaseController{
	//产品的添加
	public function add(){
		//处理表单数据
		if(IS_POST){
			//echo '<pre>';
			//var_dump(I('post.'));die();
			//生成模型
			$goodsModel= D('Goods');
			//echo '<pre>';
			//var_dump($goodsModel);die();
			//接收表单的数据  1是添加 2是修改
			if($goodsModel->create(I('post.'),1)){
				//$data = $goodsModel->create(I('post.'),1);
				//echo '<pre>';
				//var_dump($data);die();	
				//将表单中的数据插入到数据库
				if($goodsModel->add()){
					$this->success('添加成功',U('lst'));
					exit;
				}
			}
			$error = $goodsModel->getError();
			$this->error($error);
			// 4. 获取失败的原因 	
			//$error = $model->getError();
			// 5. 打印失败原因,并且在3秒之后跳回上一个页面
			//$this->error($error);
		}
		//取出会员价格
		$ml_model= D('member_level');
		$mldata = $ml_model->select();
		//var_dump($mldata);die();
		//分类
		$categoryModel = D('category');
		$categoryData = $categoryModel->getTree();
		//var_dump($categoryData);die();
		$this->assign(array(
			'categoryData'=>$categoryData,
			'mldata'      =>$mldata,
		));
		$this->display();	

	}

	//展示页面
	public function lst()
	{
		$goodsModel = D('Goods');
		//var_dump($goodsModel);die();
		$goodsData = $goodsModel->select();
		//搜索 和 翻页
		$demo = $goodsModel->search();
		$this->assign($demo);
		$this->display();
	}

   //修改页面
   public function edit(){
   	   //接收商品ID
   	   $id = I('get.id');
   	   //取出所有会员的级别
   	  
   	   $ml_model= D('member_level');
   	   $mldata = $ml_model->select();
   	   //取出会员的价格
   	   $mprice = D('member_price');
   	   $mpdata =  $mprice->where(array(
   	   	'goods_id'=>array('eq',$id),
   	   ))->select();
   	  // echo '<pre>';
   	   //var_dump($mpdata);die();
   	   //二维转一维
   	   $mp = array();
   	   foreach ($mpdata as $k=>$v){
   	   	//感觉这里用的好巧妙呀  
   	   	  $mp[$v['level_id']] = $v['price'];
   	   }
   	  // var_dump($mp);die();
   	   $goodsModel = D('Goods');
   	   if(IS_POST){
   	   
	   	   	//接收表单的数据  1是添加 2是修改
	   	   	if($goodsModel->create(I('post.'),2)){
	   	   		
	   	   		//将表单中的数据插入到数据库
	   	   		if($goodsModel->save()!== false){
	   	   			$this->success('修改成功',U('lst'));
	   	   			exit;
	   	   		}
	   	   	}
	   	   	//模型的方法是getError   
	   	   	$error = $goodsModel->getError();
	   	   	$this->error($error);
   	   }
   	   //修改商品 信息
   	   // 取出所有的分类制作下拉框
   	   $catModel = D('Category');
   	   $catData = $catModel->getTree();
   	  $goodsData =  $goodsModel->find($id);
   	  $this->assign(array(
   	  	'goodsData' => $goodsData,
   	     'mp'       => $mp,
   	  	'mldata'    => $mldata,
   	  	'catData'   =>$catData,
   	  ));
   	 /*  echo '<pre>';
   	  var_dump($goodsData);die(); */
   	  $this->display();
  }
   //删除页面
   public function del(){
   	//1 接收商品ID
   	$id = I('get.id');
   	$goodsModel = D('Goods');
    //2 删除商品
    if(false !== $goodsModel->delete($id)){
    	$this->success('删除成功');
    	exit;
    }else{
    	$this->error('删除失败');
    }	
   
   }
	
}